package com.fowo.api.datainterface.util.lingxing;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author: <a href="1006319834@qq.com">王冰卿</a>
 * @Description:
 * @Version: 1.0
 * @Date: Created in 2023/3/15 16:24
 * @Modified By:
 */
public class LingXingApiSign {

    public static String sign(Map<String, Object> params, String appSecret) {
        // 参数排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder paramNameValue = new StringBuilder();
        for (String key : keys) {
            String value = "";
//			String jsonString = JSONObject.toJSONString(params.get(key));
//			if(JSONUtil.isTypeJSONArray(jsonString)){
//				JSONArray objects = JSON.parseArray(jsonString);
//				value = objects.toJSONString();
//			}else {
            value = String.valueOf(params.get(key));
//			}
            paramNameValue.append(key).append("=").append(value.trim()).append("&");
        }
        String paramValue = paramNameValue.toString();
        if (paramValue.endsWith("&")) {
            paramValue = paramValue.substring(0, paramValue.length() - 1);
        }
        // md5加密
        String md5Hex = DigestUtils.md5Hex(paramValue.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        return AesUtil.encryptEcb(md5Hex, appSecret);
    }

    public static String signBatch(Map<String, Object> params, String appSecret) {
        // 参数排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder paramNameValue = new StringBuilder();
        for (String key : keys) {
            String value = "";
            String jsonString = JSONObject.toJSONString(params.get(key));
            if (JSONUtil.isTypeJSONArray(jsonString)) {
                JSONArray objects = JSON.parseArray(jsonString);
                value = objects.toJSONString();
            } else {
                value = String.valueOf(params.get(key));
            }
            paramNameValue.append(key).append("=").append(value.trim()).append("&");
        }
        String paramValue = paramNameValue.toString();
        if (paramValue.endsWith("&")) {
            paramValue = paramValue.substring(0, paramValue.length() - 1);
        }
        // md5加密
        String md5Hex = DigestUtils.md5Hex(paramValue.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        return AesUtil.encryptEcb(md5Hex, appSecret);
    }

}
